/*
 * The MIT License (MIT)
 * 
 * Copyright (c) [2025] [wuzjjj]
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "config.h"
#include "rcc_clk.h"
#include "delay.h"
#include "led.h"
#include "usart.h"
#include "timer.h"
#include "w25qxx.h"
#include "fontupd.h"

/*
ch340(printf):usart1	---显示当前进度
daplink:usart2+timer4 ---连接上位机软件,下发FLASH控制和数据
*/

int main(void)
{
	int i;
	RCC_ClkConfiguration();							//配置时钟
	DELAY_Init();												//延时初始化
	USART1_Init(115200);								//串口1初始化
	USART2_Init(921600);								//串口2初始化 921600
	TIM4_Int_Init(1000-1, 216-1);				//定时器4初始化,1ms,216M/1k/216=1000Hz

	LED_GPIO_Init();
	W25QXX_Init();											//W25QXX初始化
	usart2_clear_rx();									//清空串口2接收buffer
	
	delay_ms(100);
	printf("USART3:size(0x%X - %dM%dK%dB)\r\n", 
			   FLASH_SIZE,
				 GET_SIZE_M(FLASH_SIZE), 
				 GET_SIZE_K(FLASH_SIZE),
				 GET_SIZE_B(FLASH_SIZE));
	
	if(fontupd_init_and_check()) 										//检查字库
		printf("check font failed\r\n");
	else
		printf("check font success\r\n");
	
	while (1)
	{
		
		if(usart2_rx.status)							//串口2收到上位机数据
		{
			printf("usart3 received %d bytes\r\n", usart2_rx.size);
			if(usart2_rx.size > 0)
			{
				fontupd_process((u8 *)usart2_rx.buf, usart2_rx.size);
			}
			usart2_clear_rx();							//清空串口2接收buffer
			continue;
		}

		if (i % 100 == 0)
			LEDG_TOGGLE;
		
		if (i ++ > 10 * 1000)
			i = 0;

		delay_ms(1);//延时1ms
	}
}
